import { Matrix, matrixAppendMatrix } from "../math";
import { Behaviour } from "./Behaviour";
import { Serialized } from "./Serialized";


export class Transform extends Behaviour {

    @Serialized('numberInput')
    x = 0;
    @Serialized('numberInput')
    y = 0;
    @Serialized('numberInput')
    scaleX = 1;
    @Serialized('numberInput')
    scaleY = 1;
    @Serialized('numberInput')
    rotation = 0;
    @Serialized('numberInput')
    alpha = 1;

    globalAlpha = 1;

    localMatrix: Matrix;
    globalMatrix: Matrix;

    updateMatrix() {
        this.updateLocalMatrix();
        this.updateGlobalMatrix();
    }

    private updateLocalMatrix() {
        const localMatrix = new Matrix();
        localMatrix.updateFromTransform(this.x, this.y, this.scaleX, this.scaleY, this.rotation);
        this.localMatrix = localMatrix;
    }

    private updateGlobalMatrix() {

        let globalMatrix: Matrix;
        let globalAlpha: number;

        if (this.gameObject.parent) {
            const parentTransform = this.gameObject.parent.getBehaviour(Transform);
            const parentGlobalMatrix = parentTransform.globalMatrix;
            globalMatrix = matrixAppendMatrix(this.localMatrix, parentGlobalMatrix);

            const parentGlobalAlpha = parentTransform.globalAlpha;
            globalAlpha = parentGlobalAlpha * this.alpha;
        } else {
            globalMatrix = this.localMatrix;
            globalAlpha = this.alpha;
        }
        this.globalMatrix = globalMatrix;
        this.globalAlpha = globalAlpha;
    }
}
